package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TrafficPageViewBean;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.KafkaUtil;
import com.atguigu.utils.MyClickHouseUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * ClassName: Dws01TrafficVcChArIsNewPageViewWindow
 * Package: com.atguigua.app.dws
 * Description:
 *
 * @Author 周东东
 * @Create 2023/5/19 19:25
 * @Version 1.0
 */
public class Dws01TrafficVcChArIsNewPageViewWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //TODO 2.读取Kafka DWD层页面日志主题数据
        DataStreamSource<String> kafkaDS = env.fromSource(KafkaUtil.getKafkaSource("dwd_traffic_page_log", "vc_ch_ar_isnew_221109"),
                WatermarkStrategy.noWatermarks(),
                "kafka-source");

        //TODO 3.将数据转换为JSON对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        //TODO 4.按照Mid进行分组
        KeyedStream<JSONObject, String> keyedByMidDS = jsonObjDS.keyBy(json -> json.getJSONObject("common").getString("mid"));

        //TODO 5.去重Mid,并将数据转JavaBean换为对象
        SingleOutputStreamOperator<TrafficPageViewBean> trafficPageViewByMidDS = keyedByMidDS.map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {

            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("mid-state", String.class);

                //设置TTL
                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                stateDescriptor.enableTimeToLive(ttlConfig);

                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public TrafficPageViewBean map(JSONObject value) throws Exception {

                //取出状态数据
                String lastDt = valueState.value();
                long uvCt = 0L;
                long skipCt = 0L;
                String curDt = DateFormatUtil.toDate(value.getLong("ts"));
                if (lastDt == null || !lastDt.equals(curDt)) {
                    uvCt = 1L;
                    valueState.update(curDt);
                }
                JSONObject page = value.getJSONObject("page");
                if (page != null) {
                    String pageId = page.getString("page_id");
                    String lastPageId = page.getString("last_page_id");
                    if (pageId != null && lastPageId == null) {
                        skipCt = 1L;
                    }
                }

                //获取common信息
                JSONObject common = value.getJSONObject("common");

                return new TrafficPageViewBean("", "",
                        common.getString("sc"),
                        common.getString("sid"),
                        uvCt,
                        0L,
                        1L,
                        value.getJSONObject("page").getLong("during_time"),
                        skipCt,
                        value.getLong("ts"));
            }
        });
        //TODO 6.按照Sid分组
        KeyedStream<TrafficPageViewBean, String> keyedBySidDS = trafficPageViewByMidDS.keyBy(TrafficPageViewBean::getSid);

        //TODO 7.去重Sid
        SingleOutputStreamOperator<TrafficPageViewBean> trafficPageViewBySidDS = keyedBySidDS.map(new RichMapFunction<TrafficPageViewBean, TrafficPageViewBean>() {

            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("sid-state", String.class);

                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.hours(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .build();
                stateDescriptor.enableTimeToLive(ttlConfig);

                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public TrafficPageViewBean map(TrafficPageViewBean value) throws Exception {

                //获取状态数据
                String state = valueState.value();

                if (state == null) {
                    value.setSvCt(1L);
                    valueState.update("1");
                }

                return value;
            }
        });

        //TODO 8.提取时间戳生成Watermark
        SingleOutputStreamOperator<TrafficPageViewBean> trafficPageViewWithWMDS = trafficPageViewBySidDS.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<TrafficPageViewBean>() {
            @Override
            public long extractTimestamp(TrafficPageViewBean element, long recordTimestamp) {
                return element.getTs();
            }
        }));

        //TODO 9.分组、开窗、聚合
        WindowedStream<TrafficPageViewBean, String, TimeWindow> windowedStream = trafficPageViewWithWMDS.keyBy(TrafficPageViewBean::getSc).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)));

        SingleOutputStreamOperator<Object> resultDS = windowedStream.reduce(new ReduceFunction<TrafficPageViewBean>() {
            @Override
            public TrafficPageViewBean reduce(TrafficPageViewBean value1, TrafficPageViewBean value2) throws Exception {
                value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                value1.setSkipCt(value1.getSkipCt() + value2.getSkipCt());
                return value1;
            }
        }, new WindowFunction<TrafficPageViewBean, Object, String, TimeWindow>() {
            @Override
            public void apply(String key, TimeWindow window, Iterable<TrafficPageViewBean> input, Collector<Object> out) throws Exception {
                //取出数据
                TrafficPageViewBean next = input.iterator().next();

                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                next.setTs(System.currentTimeMillis());

                //输出数据
                out.collect(next);
            }
        });
        resultDS.print(">>>>>>>");
        resultDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_traffic_vc_ch_ar_is_new_page_view_window values(?,?,?,?,?,?,?,?,?)"));
        env.execute("Dws01TrafficVcChArIsNewPageViewWindow");
    }
}
